#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <cbm.h>
#include <conio.h>

#include "Buffers.h"
#include "Trim.h"
#include "Splitter.h"
#include "Drives.h"
#include "Dispatcher.h"

#pragma code-name("MKDIRCODE");
#pragma rodata-name("MKDIRCODE");

unsigned char makeDirectory(unsigned char driveIndex)
{
	unsigned char r = 0, i = 0;
	int result = 0;
	drive_t *drive = &drives[driveIndex];
	tokenCollection_t *collection = NULL;
	static char buffer[256];
	parsedPath_t *path = NULL;

//printf("\nMKDIR ..a.."); cgetc();
	if(0) cgetc();

	strcpy(buffer, buffer3);
	collection = splitString(buffer);

	if(collection->count != 2)
	{
		printf("\nusage: mkdir :dirname\n");
		free(collection);
		free(path);
		return 0;
	}

// printf("\nMKDIR ..b.."); cgetc();

	path = parsePath(1, collection, driveIndex);

// printf("\nMKDIR ..c.."); cgetc();

	driveIndex = getDrive(path->device);
	if(driveIndex == 0xFF) 
	{
		printf("\nUnknown device.");
		free(collection);
		free(path);
		return 1;
	}
	drive = &drives[driveIndex];

// printf("\nMKDIR ..d.."); cgetc();

	if(drive->type == CBM15x1)
	{
		printf("\nDrive does not support directories.");
		free(collection);
		free(path);
		return 1;
	}


// printf("\nMKDIR ..e.."); cgetc();

	if(path->file[0] == 0)
	{
		printf("\nusage: mkdir :dirname\n");
		free(collection);
		free(path);
		return 0;
	}

	
// printf("\nMKDIR ..f.."); cgetc();

	if(path->path[0] != 0)
	{
		if(drives[getDrive(path->device)].type != VICE)
		{
			sprintf(buffer3, "cd%s", path->path);
		}
		else
		{
			sprintf(buffer3, "cd:%s", path->path);
		}
		
// printf("\nMKDIR ..g.."); cgetc();

		if(!executeCommand(&drives[getDrive(path->device)], buffer3, 0))
		{
			printf("\nInvalid path.  Aborting.");
			free(collection);
			free(path);
			return 1;
		}
	}

	sprintf(buffer3, "md:%s", path->file);

//printf("\nMKDIR ..h.."); cgetc();

	r = cbm_open(15, drive->device, 15, buffer3);

	memset(buffer2, 0, sizeof(buffer2));
	result = cbm_read(15, buffer2, sizeof(buffer2));
	cbm_close(15);

//printf("\nMKDIR ..i.."); cgetc();

	if(r == 0 && buffer2[0] == '0' && buffer2[1] == '0')
	{
		printf("\nDirectory Created.");
		free(collection);
		free(path);
		return 0;
	}
	else
	{
		printf("\nERROR: %u - %s", r, buffer2);
		free(collection);
		free(path);
		return 1;
	}

}
